<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getToken } from "@/utils/auth";
import { onMounted, ref, watch, reactive } from 'vue'
import { useConfirm } from '@/hooks/useConfirm'
import { ElMessage } from 'element-plus';
import { getCurrentInstance } from 'vue';
import { productAddService, delProductService, productListService, productAllService, productUpdateService } from '@/api/stock/product.js'
const { proxy } = getCurrentInstance();  //获取当前实例
// 搜索栏数据

const validModel =  ref({
  a: '',
  b: '',
  c: ''
})

//定义函数，清空数据模型的数据
const validReset = () => {
  validModel.value = {
    a: '',
    b: '',
    c: ''
  }
}

const validateC = (rule, value, callback) => {
  if (value < validModel.value.b) {
    callback(new Error('最高价不能低于最低价'))
  } else {
    callback()
  }
}

//搜索校验规则
const validRules = reactive({
  c: [
    { validator: validateC, trigger: 'blur' },
  ]
})



//分页条数据模型
const pageNum = ref(1)//当前页
watch(pageNum, () => { loadData() })
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  loadData();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  loadData();
}

const a = ref('')
const b = ref('')
const c = ref('')

// 列表数据模型
const tableData = ref([])
/** 获取列表数据  */
const loadData = async () => {
  console.log('请求数据',validModel.value.a)
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    a: validModel.value.a ? validModel.value.a : null,
    b: validModel.value.b ? validModel.value.b : null,
    c: validModel.value.c ? validModel.value.c : null
  }
  // console.log('a',validModel.value.a ? validModel.value.a : null)
  let result = await productListService(params);
  //渲染视图
  // console.log('aaa', result.data.items)
  total.value = result.data.total;
  tableData.value = result.data.items;
}

/** 搜索按钮 */
function submitValid() {
  proxy.$refs["validRef"].validate(valid => {
    if (valid) {
          loadData();
      }
})};

onMounted(() => {
  loadData();
})

// 单选/多选判断
const single = ref(true);
const multiple = ref(true);

const ids = ref([]);
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // console.log(single.value)
};


/** 删除按钮操作 */
function handleDelete(row) {
  //点击行内的删除按钮时，row就有值
  const userIds = row.id || ids.value;
  proxy.$modal.confirm('确认删除？').then(function () {
    return delProductService(userIds);
  }).then(() => {
    loadData();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
};

// 新增/删除数据模型
const editModel = ref({
  name: '',
  price: '',
  validDays: '',
  warnNum: '',
  imgUrl: ''
})

//定义函数，清空数据模型的数据
const reset = () => {
  editModel.value = {
    name: '',
    price: '',
    validDays: '',
    warnNum: '',
    imgUrl: ''
  }
}

// 新增/编辑标题
const title = ref('')

// 新增/编辑标题
const dialogVisible = ref(false)

// 展示新增/编辑标题（标签中修改值不需要.value，函数中需要加.value）
const showDialog = (row) => {
  reset()
  dialogVisible.value = true;
  title.value = '编辑商品';
  //   console.log('row ',row.supplier)
  // 对ref对象的属性赋值
  editModel.value.name = row.name;
  editModel.value.price = row.price;
  editModel.value.validDays = row.validDays;
  editModel.value.imgUrl = row.imgUrl;
  editModel.value.warnNum = row.warnNum;
  //   console.log('model ',editModel.value.supplier)
  //扩展id属性，将来需要传递给后台，不需要定义
  editModel.value.id = row.id
}

// 表单验证
const rules = reactive({
  name: [
    { required: true, message: '请输入商品名', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入单价', trigger: 'blur' },
  ],
  validDays: [
    { required: true, message: '请输入有效天数', trigger: 'blur' },
  ],
  warnNum: [
    { required: true, message: '请输入库存预警值', trigger: 'blur' },
  ]
})

/** 提交按钮 */
function submitForm() {
  proxy.$refs["addRef"].validate(valid => {
    if (valid) {
      // id != undefined标明有选中行，为新增，否则为修改
      if (editModel.value.id != undefined) {
        productUpdateService(editModel.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          dialogVisible.value = false;
          loadData();
        });
      } else {
        productAddService(editModel.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          dialogVisible.value = false;
          loadData();
        });
      }
    }
  });
};

// 搜索栏
const isExpand = ref(false)

const header = ref('')
header.value = "Bearer " + getToken()


// 文件上传（导入）

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: "http://localhost:8080/product/import"
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  console.log('成功')
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  loadData();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};

// 导出
/** 导出按钮操作 */
// function handleExport() {
//   location.href = "/product/export"
// };

/** 导出按钮操作 */
const handleExport = async () => {

proxy.download("/product/export", {},`商品_${new Date().getTime()}.xlsx`);

}

//回收站
const visibleDrawer = ref(false)

//上传图片
const uploadImg=(r)=>{
		editModel.value.imgUrl=r.data
}

</script>
<template>
  <el-card class="page-container">
    <!-- <template #header>
      <div class="header">
        <span>商品管理</span>
      </div>
    </template> -->

    <!-- 筛选 -->
    <el-form inline ref="validRef" :model="validModel"  :rules="validRules">
        <el-form-item label="商品名称" prop="a">
          <el-input placeholder="请输入商品名称" v-model="validModel.a" />
        </el-form-item>
        <el-form-item label="最低价" prop="b">
          <el-input placeholder="最低价" v-model.number="validModel.b" type="number" oninput ="value=value.replace(/[^\d]/g,'')" style="width:120px;">
            <template #suffix>元</template>
          </el-input> 
        </el-form-item>
        <el-form-item label="最高价" prop="c">
          <el-input placeholder="最高价" v-model.number="validModel.c" type="number" oninput ="value=value.replace(/[^\d]/g,'')" style="width:120px;" min="b">
            <template #suffix>元</template>
          </el-input> 
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitValid()"> <span class="iconfont icon-sousuo"></span>搜索 </el-button>
          <el-button type="default" @click="validReset()"> 重置 </el-button>
        </el-form-item>
    </el-form>

    <!-- 按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus"
          @click="dialogVisible = true; title = '添加商品'; reset()">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>

    </el-row>
    <!-- 按钮组 -->
    <!-- 表格 -->
    <el-table :data="tableData" :border="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" fixed="left"></el-table-column>
      <el-table-column label="序号" width="60" type="index" align="center">
        <!-- 序号重新计算 -->
        <template #default="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
      <el-table-column label="单价" prop="price" align="center"></el-table-column>
      <el-table-column label="图例" align="center" >
		  <template #default="scope">
		     <el-image style="width:80px;height:80px" :src="scope.row.imgUrl"></el-image>
		  </template>
	    </el-table-column>
      <el-table-column label="有效天数" prop="validDays" align="center"></el-table-column>
      <el-table-column label="库存预警值" prop="warnNum" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="130" fixed="right">
        <template #default="{ row }">
          <el-button :icon="Edit" type="primary" link size="small" @click="showDialog(row)">
            <span class="iconfont icon-bianji"></span>修改
          </el-button>
          <el-button :icon="Delete" type="primary" link size="small" @click="handleDelete(row)">
            <span class="iconfont icon-shanchu"></span>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格 -->
    <!-- 分页 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
      @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
    <!-- 分页 -->

    <!-- 添加/编辑菜单 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form ref="addRef" :model="editModel" :rules="rules" label-width="100px" style="padding-right: 30px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editModel.name"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="editModel.price"></el-input>
        </el-form-item>
        <el-form-item label="有效天数" prop="validDays">
          <el-input v-model="editModel.validDays" type="number" oninput ="value=value.replace(/[^\d]/g,'')"></el-input>
        </el-form-item>
        <!-- <el-form-item label="库存预警值" prop="warnNum">
          <el-input v-model="editModel.warnNum" type="number" oninput ="value=value.replace(/[^\d]/g,'')"></el-input>
        </el-form-item> -->
        <el-col>
          <el-form-item label="图例" >
            <el-upload class="upload-demo" drag :on-success="uploadImg"
              action="http://127.0.0.1:8080/resource/uploadimg"
              :headers="{'Authorization': header}"
              :limit="1"
              >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                请把上传的图片拖拽到这里 <em>或者点击选择上传的文件</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  图片只支持png、jpg等格式的文件
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm()"> 确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回收站抽屉 -->
    <el-drawer v-model="visibleDrawer" title="回收站" direction="rtl" size="50%">
      <div style="margin-bottom: 8px">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">彻底删除</el-button>
      </div>
      <el-table :data="tableData" :border="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" fixed="left"></el-table-column>
      <el-table-column label="序号" width="60" type="index" align="center">
        <!-- 序号重新计算 -->
        <template #default="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
      <el-table-column label="供应商" prop="supplier" align="center"></el-table-column>
      <el-table-column label="单价" prop="price" align="center"></el-table-column>
      <el-table-column label="图例" prop="imgUrl" align="center"></el-table-column>
      <el-table-column label="到期时间" prop="expireTime" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template #default="{ row }">
          <el-button :icon="Delete" type="primary" link size="small" @click="handleDelete(row)">
            <span class="iconfont icon-shanchu"></span>彻底删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-drawer>

  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .mb8 {
    margin-bottom: 8px;
  }
}
</style>